<template>
  <view class="card">
    <uni-section title="单位基本信息" type="line">
      <view class="formItem">
        <view class="label required">单位名称</view>
        <input class="content" v-model="form.name" placeholder="请输入单位名称" />
      </view>
      <view class="tip">单位名称应与营业执照或社会统一信用代码证书上一致</view>

      <view class="formItem">
        <view class="label required">统一信用代码</view>
        <input class="content" v-model="form.code" placeholder="请输入统一社会信用代码" />
      </view>

      <view class="formItem">
        <view class="label required">单位类别</view>
        <picker mode="selector" class="content" range-key="dictLabel" :range="unitList" @change="typeChange">
          <view :style="{ color: form.types ? '#333' : '#999' }">{{ form.types || '请选择单位类别' }}</view>
        </picker>
      </view>

      <view class="formItem" v-if="show">
        <view class="label required">所在区域</view>
        <view :style="{ color: form.areas ? '#333' : '#999' }" @click="openLevel">{{ form.areas || '请选择所在区域' }}</view>
        <level-linkage ref="levelLinkage" :pickerValueDefault="pickerValueDefault" :allData="treeData"
          @onConfirm="onConfirm" themeColor='#007AFF'></level-linkage>
      </view>

      <view class="formItem" @click="chooseMap">
        <view class="label required">单位坐标</view>
        <view :style="{ color: form.coordinate ? '#333' : '#999' }">{{ form.coordinate || '请选择单位坐标' }}</view>
      </view>

      <view class="formItem">
        <view class="label required">单位详细地址</view>
        <input class="content" v-model="form.address" placeholder="请输入单位详细地址" />
      </view>

      <view class="formItem">
        <view class="label ">成立时间</view>
        <picker mode="date" class="content" :value="date" :start="startDate" :end="endDate" @change="signChange">
          <view :style="{ color: form.establishTime ? '#333' : '#999' }">{{ form.establishTime || '请选择成立时间' }}</view>
        </picker>
      </view>

      <view class="formItem">
        <view class="label required">单位登录账号</view>
        <input class="content" v-model="form.userName" placeholder="请输入单位登录账号" />
      </view>
      <view class="tip">单位登录账号说明：</view>
      <view class="tip">1、如果是单一经营场所，请与单位名称保持一致，例如“XX市维也纳酒店有限公司”“XX市嘉华物业管理有限公司”；</view>
      <view class="tip">2、如果是连锁经营单位，“单位登录账号”应该由单位名称+道路名称组成，例如"XX市维也纳酒店管理有限公司北京路店"；</view>
      <view class="tip">3、如果是物业公司，“单位登录账号”应该由单位名称+小区（或物业）名称组成，例如“XX市嘉华物业管理有限公司光明小区”；</view>

      <view class="formItem">
        <view class="label required">消防安全责任人（法人代表）</view>
        <input class="content" v-model="form.headName" placeholder="请输入责任人姓名" />
      </view>

      <view class="formItem">
        <view class="label required">责任人联系电话</view>
        <input class="content" v-model="form.headPhone" @blur="checkPhone('headPhone', '责任人联系电话')"
          placeholder="请输入责任人联系电话" />
      </view>

      <view class="formItem">
        <view class="label required">消防安全管理姓名</view>
        <input class="content" v-model="form.manageName" placeholder="请输入消防安全管理人" />
      </view>

      <view class="formItem">
        <view class="label required">管理人联系电话</view>
        <input class="content" v-model="form.managePhone" @blur="checkPhone('managePhone', '管理人联系电话')"
          placeholder="请输入管理人联系电话" />
      </view>

      <view class="formItem">
        <view class="label required">单位所在楼层</view>
        <input class="content" v-model="form.floor" placeholder="请输入单位所在楼层" />
      </view>

      <view class="formItem">
        <view class="label required">各楼层使用功能</view>
        <input class="content" v-model="form.floorUseFunction" placeholder="请描述各楼层使用功能" />
      </view>

      <view class="formItem">
        <view class="label required">建筑面积</view>
        <input class="content" type="digit" v-model.number="form.areaSize" placeholder="请输入建筑面积" @blur="changeArea" />
      </view>

      <view class="formItem" style="min-height: 110rpx; height: auto">
        <view class="label ">消防设施情况</view>
        <ld-select :multiple="true" :list="array" class="content" label-key="dictLabel" value-key="dictValue"
          placeholder="请选择" v-model="form.facilitie" @change="selectChange"></ld-select>
      </view>

      <view class="formItem">
        <view class="label ">职工人数</view>
        <input class="content" v-model.number="form.number" type="number" placeholder="请输入职工人数" />
      </view>

      <view class="formItem">
        <view class="label ">单位简介</view>
        <input class="content" v-model="form.companyProfile" placeholder="请输入单位简介" />
      </view>

      <view class="formItem">
        <view class="label required">填表人</view>
        <input class="content" v-model="form.writeBy" placeholder="请输入填表人姓名" />
      </view>

      <view class="formItem">
        <view class="label required">联系电话</view>
        <input class="content" v-model="form.writePhone" @blur="checkPhone('writePhone', '填表人联系电话')"
          placeholder="请输入联系电话" />
      </view>

      <view class="formItem_doubleRow">
        <view class="label">营业执照</view>
        <upload-img :imgList="imageValue" @changeImage="uploadSuccess($event)"></upload-img>
      </view>
    </uni-section>
    <view style="height: 100rpx;"></view>

  </view>
</template>
<script>
import {
  baseImgUrl
} from "@/config.js";
import UploadImg from "../../../components/upload/upload-img.vue";
import levelLinkage from "@/components/three-level-linkage/linkage.nvue"
import { checkPhoneTools } from '@/utils/tools.js'
export default {
  components: {
    UploadImg,
    levelLinkage
  },
  data() {
    return {
      imageValue: [],
      baseImgUrl: baseImgUrl,
      form: {
        name: "", // 单位名称
        code: "", // 统一社会信用代码
        type: "", // 单位类别（代码）
        types: '', // 单位类别（中文）
        area: "", // 所在区域（代码）
        areas: "", // 所在区域（中文）
        coordinate: "", // 单位坐标
        address: "", // 单位详细地址
        userName: "", // 单位登录账号
        establishTime: "", // 成立时间
        headName: "", // 责任人姓名
        headPhone: "", // 责任人联系电话
        manageName: "", // 消防安全管理人姓名
        managePhone: "", // 管理人联系电话
        floor: "", // 单位所在楼层
        floorUseFunction: "", // 各楼层使用功能
        areaSize: "", // 建筑面积
        facilitie: [], // 消防设施情况(展示)
        facilities: '', // 消防设施情况(上传)
        number: "", // 职工人数
        companyProfile: "", // 单位简介
        writeBy: "", // 填表人
        writePhone: "", // 联系电话
        businessLicense: "", // 营业执照
      },

      pickerValueDefault: [0, 0, 0],
      treeData: [], // 所属区域
      array: [], // 消防设施情况
      show: false, // 所属区域的展示
      unitList: [],

      date: null,
      startDate: null,
      endDate: null,
    };
  },
  created() {
    this.getTreelists()
    this.getzidian()
    this.getUnitList()
  },
  methods: {
    getzidian() {
      this.$store
        .dispatch("getFaciliList", 2)
        .then(({ code, data, msg }) => {
          if (code == 200) {
            this.array = data;
          } else {
            uni.showToast({
              title: msg || "获取设施列表失败",
              icon: "error",
            });
          }
        });
    },
    getUnitList() {
      this.$getDict('unit_type').then(res => {
        this.unitList = res
      })
    },
    selectChange(e) {
      this.$set(this.form, 'facilitie', e)
      let facilities = this.form.facilitie.join(',')
      this.$set(this.form, 'facilities', facilities)
    },
    getTreelists() {
      this.$store.dispatch('getAreaTreeApi').then(res => {
        if (res.length != 0) {
          this.treeData = res.data
          this.show = true
        }
      })
    },
    // 手机号校验
    checkPhone(label, msg) {
      const phone = this.form[label];
      return checkPhoneTools(phone, `请输入正确的${msg}`)
    },
    // 选择企业地理坐标
    chooseMap() {
      let that = this
      uni.getLocation({
        type: "gcj02", //返回可以用于uni.openLocation的经纬度
        success: function (res) {
          console.log(res, '这里的经纬度是啥');
          const latitude = res.latitude;
          const longitude = res.longitude;
          uni.chooseLocation({
            latitude: latitude,
            longitude: longitude,
            success: (res) => {
              if (res) {
                that.form.address = res.address;
                that.form.coordinate = res.longitude + "," + res.latitude;
              }
            },
            fail: (e) => {
              console.log(e)
            }
          });
        },
      });
    },
    // 成立时间
    signChange(e) {
      this.$set(this.form, "establishTime", e.detail.value);
    },
    // 上传成功回调函数
    uploadSuccess(e) {
      let str = e.join(",");
      this.$set(this.form, "businessLicense", str);
    },
    changeArea(e) {
      let dist = e.detail.value.split('.')
      if (dist.length > 2) {
        uni.showModal({
          title: '提示',
          content: "请输入正确的建筑面积",
        });
        this.$set(this.form, "areaSize", null)
      }
    },
    //! 提供给父组件的校验方法，错误时返回表单名
    validateForm() {
      let result = true;
      // 责任人联系电话
      const headPhone = this.form.headPhone;
      // 管理人联系电话
      const managePhone = this.form.managePhone;
      // 联系电话
      const writePhone = this.form.writePhone;
      const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      if (!reg.test(headPhone)) {
        return "责任人联系电话、";
      }
      if (!reg.test(managePhone)) {
        return "管理人联系电话、";
      }
      if (!reg.test(writePhone)) {
        return "联系电话、";
      }
      // 如果表单字段为空时则返回校验失败
      for (const key in this.form) {
        if (this.form[key] === "") {
          result = "单位基本信息、";
          break;
        }
      }
      return result;
    },

    openLevel() {
      this.$refs.levelLinkage.open();
    },
    onConfirm(e) {
      this.$set(this.form, 'areas', e.name)
      this.$set(this.form, 'area', e.thirdPick.id)
    },
    typeChange(e) {
      let obj = this.unitList[e.detail.value]
      this.$set(this.form, 'type', obj.dictValue)
      this.$set(this.form, 'types', obj.dictLabel)
    }
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.formItem_address {
  width: 65%;
  height: 36rpx;
}

.required {
  &::before {
    content: "*";
    margin: 0 10rpx;
    color: #ea0707;
  }
}

.content1 {
  display: flex;
  overflow: auto;
  width: 70%;
}

::v-deep .uni-section {
  background-color: transparent !important;
  margin-top: 0 !important
}

::v-deep .uploadImg {
  padding: 0 !important;

  .cu-form-group {
    padding: 0 !important;
    max-height: 200rpx !important;

    .grid.col-4.grid-square>uni-view {
      padding-bottom: calc((100% - 100px) / 2) !important;
      height: 0;
      width: calc((100% - 100px) / 2) !important;
    }

    .grid.grid-square>uni-view {
      margin-right: 0;
      margin-bottom: 0;
    }
  }
}

::v-deep .input-placeholder {
  font-size: 28rpx;
  color: #999
}

::v-deep .uni-picker-container .uni-picker-action.uni-picker-action-confirm {
  color: $OVERALL_SITUATION_BACKGROUND !important
}
</style>
